package thread.safe;

import interface_test.sharp.C;

/**
 * @author Dianzhi Han
 * @version 1.0
 * @description: 多线程场景下的线程安全问题
 * @date 2022/10/29 22:12
 */
public class ThreadUnsafeDemo {
    private static class Counter {
        public int getCount() {
            return count;
        }
        //只能保证可见性
        volatile int count = 0;
        void increase() {
            count ++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        // t1将count值 + 5w
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        },"t1");
        // t2也将count值 + 5w
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // t1 -> t2 -> main
        // 主线程走到此处，说明t1和t2都已经执行结束，理想状态count = 10w
        System.out.println("两个搬砖人都已经执行结束");
        System.out.println(counter.count);
    }

}